package com.buba.livenuniappservernew.api.recipe.controller;

import com.buba.livenuniappservernew.api.recipe.entity.Recipe;
import com.buba.livenuniappservernew.api.recipe.service.RecipeService;
import com.buba.livenuniappservernew.common.CommonResult;
import com.buba.livenuniappservernew.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
/**
 * <p>
 * 食谱管理表
 前端控制器
 * </p>
 *
 * @author mading
 * @since 2024-09-04
 */
@RequestMapping("/RecipeController")
@RestController
@CrossOrigin
public class RecipeController {
    @Autowired
    RecipeService recipeService;
    @Autowired
    RedisUtil redisUtil;
    /**
     * 全查食谱
     * 如果携带参数 根据参数查询
     * @return
     */
    @GetMapping("/listRecipe")
    public CommonResult listRecipe(Integer footType){
        if (footType == null){
            //获取全查食谱
            List<Object> objectList1 = redisUtil.lGet("listRecipeRecommended1", 0, -1);
            List<Object> objectList2 = redisUtil.lGet("listRecipeRecommended2", 0, -1);
            if (!objectList1.isEmpty() && objectList1 != null){
                return CommonResult.success(objectList1);
            }
            if(!objectList2.isEmpty() && objectList2 != null){
                redisUtil.lSet("listRecipeRecommended1",objectList1,100000);
                return CommonResult.success(objectList2);
            }
            return recipeService.listRecipe(footType);
        }
        String redisKey1;
        String redisKey2;
        int time1 = 100000;
        if (footType == 0) {
            redisKey1 = "vegetableRecipe1";
            redisKey2 = "vegetableRecipe2";
        } else if (footType == 1) {
            redisKey1 = "meatRecipe1";
            redisKey2 = "meatRecipe2";
        } else if (footType == 2) {
            redisKey1 = "LowInFatRecipe1";
            redisKey2 = "LowInFatRecipe2";
        } else {
            redisKey1 = "listRecipeRecommended1";
            redisKey2 = "listRecipeRecommended2";
        }

        List<Object> list1 = redisUtil.lGet(redisKey1, 0, -1);
        if (!list1.isEmpty()) {
            return CommonResult.success(list1);
        }
        List<Object> list2 = redisUtil.lGet(redisKey2, 0, -1);
        if (!list2.isEmpty()) {
            redisUtil.lSet(redisKey1, list2, time1);
            return CommonResult.success(list2);
        }

        return recipeService.listRecipe(footType);

    }
}
